package web.servlets;

import domain.Account;
import domain.Cart;
import domain.CartItem;
import domain.Item;
import persistence.CartDAO;
import persistence.Impl.CartDAOImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class ViewCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CartDAOImpl cartDAO = new CartDAOImpl();
        HttpSession session = req.getSession();
        if(session.getAttribute("username")!=null) {
            Cart cart = (Cart) session.getAttribute("cart");
            Account account = (Account) session.getAttribute("account");
            if (cart == null) {
                cart = new Cart();
                session.setAttribute("cart", cart);
            }
            if (account != null) {
                List<CartItem> cartItems = cartDAO.getCartItemIdByUserName(account.getUsername());
                for (CartItem cartItem : cartItems) {
                    Item item = cartItem.getItem();
                    cart.addItem(item, true);
                    cart.setQuantityByItemId(item.getItemId(), cartItem.getQuantity());
                }
            }
            req.getRequestDispatcher(VIEW_CART).forward(req, resp);
        }else{
            session.setAttribute("message","Please sign in before you use cart");
            req.getRequestDispatcher(ERROR).forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
